<template>
  <div>
    <avue-crud
    v-if="option.column"
    :data="data.data"
    :option="option"
    :page.sync="page"
    @row-save="create"
    @row-update="update"
    @row-del="remove"
    @on-load="changePage"
    @sort-change="changeSort"
     @search-change="searchChange"
    >
    </avue-crud>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'

@Component({})
export default class CourseList extends Vue {
  @Prop(String) resource!: string
  data: any = {}
  option: any = {}

  page: any = {
    total: 0
    // pageSize: 2,
    // pageSizes: [2, 5, 10]
  }

  query: any = {
    // sort: { _id: -1 }
  }

  async fetch () {
    const res = await this.$axios.get(`${this.resource}`, {
      params: {
        query: this.query
      }
    })
    this.page.total = res.data.total
    this.data = res.data
  }

  async fetchOption () {
    const res = await this.$axios.get(`${this.resource}/option`)
    this.option = res.data
  }

  async changePage (page: any) {
    // console.log(page)
    this.query.page = page.currentPage
    this.query.limit = page.pageSize
    this.fetch()
  }

  async changeSort (sortParams: any) {
    const prop: any = sortParams.prop
    const order: any = sortParams.order
    if (!order) {
      this.query.sort = null
    } else {
      this.query.sort = {
        [prop]: order === 'ascending' ? 1 : -1
      }
    }
    this.fetch()
  }

  async searchChange (where: any, done: any) {
    done()
    for (const k in where) {
      const field = this.option.column.find(function (v: any) {
        return v.prop === k
      })
      if (field.regex) {
        where[k] = { $regex: where[k] }
      }
    }
    this.query.where = where
    this.fetch()
  }

  async create (row: any, done: any, loading: any) {
    await this.$axios.post(`${this.resource}`, row)
    this.$message('创建成功')
    this.fetch()
    done()
  }

  async update (row: any, index: any, done: any, loading: any) {
    const data = JSON.parse(JSON.stringify(row))
    delete data.$index
    await this.$axios.put(`${this.resource}/${row._id}`, data)
    this.$message('更新成功')
    this.fetch()
    done()
  }

  async remove (row: any, index: any) {
    try {
      await this.$confirm('是否确认删除？')
    } catch (e) {
      return
    }
    await this.$axios.delete(`${this.resource}/${row._id}`)
    this.$message.success('删除成功')
    this.fetch()
  }

  created () {
    this.fetch()
    this.fetchOption()
  }
}
</script>

<style>

</style>
